#!/bin/bash

if [[ $1 == "" ]]; then
  echo "Specify directive for operation."
  exit 1
fi

if [[ $2 == "" ]]; then
  echo "Specify domain for operation."
  exit 1
fi

directive=$1
domain=$2
spec=$3


start_all () {
  if [ -n "$spec" ]; then
    virsh list --all | grep shut | grep $spec | awk '{print $2}' | xargs -i virsh start {}
  else
    virsh list --all | grep shut | awk '{print $2}' | xargs -i virsh start {}
  fi
  echo start all vms.
}

stop_all () {
  virsh list --all | grep running | awk '{print $2}' | xargs -i virsh shutdown {}
  echo stop all vms.
}

destroy_all() {
  virsh list --all | grep shut | awk '{print $2}' | xargs -i virsh undefine {}
}

undefine_all () {
  for vm in $(virsh list --all | grep shut | awk '{print $2}'); do
    for snap in $(virsh snapshot-list $vm --name); do
      virsh snapshot-delete $vm $snap
      echo snapshot delete $vm $snap
    done
    virsh undefine $vm
    echo undefine $vm
  done
  echo undefine all vms.
}

if [[ $1 == "start" ]]; then
  if [[ $2 == "all" ]]; then
    start_all
  fi
elif [[ $1 == "stop" ]]; then
  if [[ $2 == "all" ]]; then
    stop_all
  fi
elif [[ $1 == "delete" ]]; then
  if [[ $2 == "all" ]]; then
    stop_all
    undefine_all
  fi
fi

